package com.sdImg.service;

import com.ruoyi.common.config.RuoYiConfig;
import com.sdImg.parameters.Img2ImgParameter;
import com.sdImg.parameters.SamplerEnums;
import com.sdImg.request.Img2Img;
import com.sdImg.res.SdResponses;
import com.zhucx.ZhuCrawler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class GenImgService {
    private static Logger logger = LoggerFactory.getLogger(GenImgService.class);


    public static void main(String[] args) {

//        try {
//            FileInputStream inputStream = new FileInputStream("C:\\Users\\竹子\\Desktop\\图\\12.jpg");
//            BufferedImage image = ImageIO.read(inputStream);
//            int width = image.getWidth();
//            int height = image.getHeight();
//            System.out.println(width+"/"+height);
//            // 在这里获取到图片的尺寸信息
//            // ...
//            inputStream.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//            logger.error(e.getMessage());
//        }
        int w = 800; int h = 600;
        Random random = new Random();
        Map<String,Integer> map = new HashMap<String,Integer>();
        double[] scaleRatios = {1.2,1.3,0.8,0.7,1.1,0.9};
        int no = random.nextInt(6);
        double scaleRatio = scaleRatios[no];
        int targetWidth = (int) (w * scaleRatio);
        int targetHeight = (int) (h * scaleRatio);
        map.put("w",targetWidth);
        map.put("h",targetHeight);
        System.out.println(map);

    }

    /**
     * 图生图
     * @throws IOException
     */
    public boolean img2img(String sourceImg,String targetImg,String prompts)  {
        boolean hasSuccess = false;
        Img2ImgParameter parameter = new Img2ImgParameter(RuoYiConfig.getSdApi());
        int width = 500;
        int height = 500;
        //资源图信息
        try {
            FileInputStream inputStream = new FileInputStream(sourceImg);
            BufferedImage image = ImageIO.read(inputStream);
             width = image.getWidth();
             height = image.getHeight();
//            System.out.println(width+"/"+height);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();

            return hasSuccess;
        }
        Map<String,Integer> whMap = scaleRatio(width,height);
        int targetW = whMap.get("w");
        int targetH = whMap.get("h");
        //重绘幅度
        parameter.setDenoisingStrength(new BigDecimal("0.39"));
        parameter.setSeed(-1);
        parameter.setSteps(30);
        parameter.setCfgScale(7);
        parameter.setWidth(targetW);
        parameter.setHeight(targetH);
        parameter.setSamplerName(SamplerEnums.DPM_2M_Karras.getInfo());
        Path path = Paths.get(sourceImg);
        try {
            byte[] bytes = Files.readAllBytes(path);
            Base64.Encoder encoder = Base64.getEncoder();
            String base64String = encoder.encodeToString(bytes);
            parameter.setInit_images(new String[]{base64String});
            parameter.setPrompt("High definition movies, delicate and realistic"+prompts);
//		parameter.setPrompt("Braised pork belly, home-made, delicious");
            parameter.setNegativePrompt("");
            SdResponses res = Img2Img.generate(parameter);
            for (String image : res.getImages()) {
                BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(image)));
                File output = new File(targetImg);
                ImageIO.write(bufferedImage, "png", output);
//			System.out.println(res.getInfo());
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return hasSuccess;
        }
        return true;

    }


    /**
     *  重置长宽比
     * @param w
     * @param h
     * @return
     */
    public Map<String,Integer> scaleRatio(Integer w,Integer h){
        Random random = new Random();
        Map<String,Integer> map = new HashMap<String,Integer>();
        double[] scaleRatios = {1.2,1.3,0.8,0.7,1.1,0.9};
        int no = random.nextInt(6);
        double scaleRatio = scaleRatios[no];
        int targetWidth = (int) (w * scaleRatio);
        int targetHeight = (int) (h * scaleRatio);
        map.put("w",targetWidth);
        map.put("h",targetHeight);
        return map;
    }


}
